package com.eshipenet.shipnet.commplanrpc.util;

import com.eshipenet.shipnet.commplan.Query;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import scala.collection.Seq;
import scala.util.Try;
import squirrel.JSONQuery;
import squirrel.ParameterizedSQL;
import squirrel.SqlSelectAst;
import squirrel.SqlValue;

import java.util.ArrayList;

public class FormatSql {

    public static Log log = LogFactory.getLog(FormatSql.class);


    public static Query getFormatSql(JSONQuery jsonQuery) {

        Query query = new Query();

        String sql = "";

        Try<SqlSelectAst> ast = jsonQuery.toSqlAst();

        boolean isSuccess = ast.isSuccess();

        try{

            if (!isSuccess) {
                log.error("ast--isSuccess:" + ast.failed());
                throw new Exception("ast.failed():"+ast.failed());
            } else {

                Try<ParameterizedSQL> toSql = ast.get().toSQL();
                isSuccess = toSql.isSuccess();

                if (!isSuccess) {
                    log.error("toSql--isSuccess:" + toSql.failed());
                    throw new Exception("toSql.failed():"+toSql.failed());
                } else {
                    query.setSql(toSql.get().sql());
                    query.setWhere(toSql.get().args());


                }

            }

            return query;

        }catch (Exception e){
           e.printStackTrace();
        }

        return query;
    }



    public static Object[] sqlValueToObject(Seq<SqlValue> value) {

        scala.collection.Iterator<SqlValue> iterator = value.seq().iterator();

        java.util.List<Object> it_list = new ArrayList<Object>();

        while (iterator.hasNext()) {
            it_list.add(iterator.next().toValue());
        }

        return it_list.toArray(new Object[0]);

    }



}

